﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using MS.Data.API.Read.Command;
using MS.Data.Domain;
using MS.Data.ErrorCode;
using System.IdentityModel.Tokens.Jwt;
using System.Text;

namespace MS.Data.API.Read.Controllers
{
    /// <summary>
    /// API控制器-读
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MangController : ControllerBase
    {
        IMediator mediator;
        ILogger<MangController> logger;

        public MangController(IMediator mediator, ILogger<MangController> logger)
        {
            this.mediator = mediator;
            this.logger = logger;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="login">请求</param>
        /// <returns>返回结果</returns>
        [HttpPost]
        public Task<APIResult<UserDto>> login(LoginCommand login)
        {
            return mediator.Send(login);
        }
        /// <summary>
        /// 测试日志
        /// </summary>
        /// <returns>返回结果</returns>
        [HttpGet]
        [Authorize]
        public IActionResult Nlog()
        {
            int a=0,b=0;
            int c=0;
            c = a / b;
            return Ok(c);
        }
        /// <summary>
        /// 显示权限列表
        /// </summary>
        /// <returns>返回结果</returns>
        [HttpGet]
        public Task<APIResult<APIPing<Permission>>> GetPermission([FromQuery] GetPermissionCommand getPermission)
        {

            return mediator.Send(getPermission);
        }
        /// <summary>/// 生成 JWT Token（令牌）/// </summary>/// <returns></returns>
        private string CreateTokenString()
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
